<script setup>
import {ajax} from 'framework'
import {ref, reactive} from 'vue'
import {message} from 'heyui'
import {useRoute} from 'vue-router'

const route=useRoute()

const types = ['string', 'number', 'boolean', 'array', 'int', 'float']
const paramsTable = ref([])
const responseTable=ref([])
//事件
//Props Open方法传入的参数
const {params, dialog} = defineProps({
  params: Object,
  dialog: Object
})

//dialog.cancel() 方法可以直接关闭对话框
//打开Dialog时进行初始化
let isAdd = false
if (params) {
  //通知Dialog处于loading状态
  dialog.loading(true)
  ajax.get("function/detail", params).then(r => {
    Object.assign(data, r.data)
    if(data.parameters){
      let parameters=JSON.parse(data.parameters)
      let params=[]
      let required=parameters.required||[]
      for(let p in parameters.properties){
        let item= parameters.properties[p]
        params.push({
          name:p,
          type:item.type,
          required:required.indexOf(p)>-1,
          description:item.description
        })
      }
      paramsTable.value=params
    }
    if(data.responses){
      let parameters=JSON.parse(data.responses)
      let params=[]
      let required=parameters.required||[]
      for(let p in parameters.properties){
        let item= parameters.properties[p]
        params.push({
          name:p,
          type:item.type,
          required:required.indexOf(p)>-1,
          description:item.description
        })
      }
      responseTable.value=params
    }


    dialog.loading(false)
  })
} else {
  isAdd = true
}
const methods = ref([])
const perMethods=ref([])
ajax.get("function/fun_infos").then(r => {
  r.data.forEach(it => it.title = it.name + "(" + it.path + ")")
  methods.value = r.data
  console.log(r.data)
  perMethods.value=r.data.filter(it=>it.parameters.length==0)
})
const onScriptChange = (v) => {
  data.description = v.description
  data.parameters = JSON.stringify(v.parameters)
  let params= paramsTable.value = []
  for(let p of v.parameters){
    params.push({
      name:p.name,
      type:p.dataType.toLowerCase(),
      required:p.required,
      description:p.description
    })
  }

  console.log(v)
}
//属性和状态
let form = ref(null)

//表单数据
const data = reactive({
  id: null,
  name: null,
  description: null,
  parameters: null,
  responses: null,
  examples: null,
  appId: route.query.app,
  vector: null,
  direct: null,
  script: null,
  perScript: null,
})

//验证规则
const rules = {}

/**
 * 提交数据
 */
dialog.onSubmit(() => {
  let validResult = form.value.valid();
  if (validResult.result) {
    //放入请求参数描述
    let required=[]
    let parameters={
      type:"object",
      properties:{}
    }
    for(let p of paramsTable.value){
      let prop=parameters.properties[p.name]={
        type:p.type,
        description:p.description
      }
      if(p.enum){
        prop.enum=p.enum
      }
      if(p.required){
        required.push(p.name)
      }
    }
    if(required.length>0){
      parameters.required=required
    }
    data.parameters=JSON.stringify(parameters)
    //放入响应
    if(responseTable.value.length>0){
      let respFields={
        type:"object",
        properties:{}
      }
      for(let p of responseTable.value){
        let prop=respFields.properties[p.name]={
          type:p.type,
          description:p.description
        }
        if(p.enum){
          prop.enum=p.enum
        }
      }
      data.responses=JSON.stringify(respFields)
    }

    dialog.loading(true)
    ajax.post(isAdd ? 'function/add' : 'function/save', data).then(r => {
      message("已保存")
      dialog.success(r.data)
    }).catch(e => {
      message.error(e.message)
    }).finally(f => dialog.loading(false))
  }
})
function openEditor(){
  if(data.script){
    //_tab
    // let tabs=JSON.parse(localStorage['magic-recent_opened_tab']||'[]')
    // if(tabs.indexOf(data.script)==-1){
    //   tabs.push(data.script)
    // }
    // localStorage['magic-recent_opened_tab']=JSON.stringify(tabs)
    localStorage['magic-recent_opened_tab']=JSON.stringify([data.script])
  }else{
    delete  localStorage['magic-recent_opened']
  }
  window.open('./developer/index.html','code_editor')
}
function addResp(){
  responseTable.value.push({name:'prop',type:'string'})
}
function addParam(){
  paramsTable.value.push({name:'param',type:'string'})
}
function delParam(it){
  let i=  paramsTable.value.indexOf(it)
  if(i>-1){
    paramsTable.value.splice(i,1)
  }
}
function delRespProp(it){
  let i=  responseTable.value.indexOf(it)
  if(i>-1){
    responseTable.value.splice(i,1)
  }
}

</script>
<template>
  <Form :model="data" :rules="rules" mode="twocolumn" ref="form" style="width: 800px;">
    <FormItem label="名称" prop="name" required single>
      <Input type="text" v-model="data.name"/>
    </FormItem>
    <FormItem label="处理函数" prop="script" required single>
      <div class="h-input-group">
        <Select :datas="methods" keyName="id" titleName="title" v-model="data.script" :filterable="true"
              @change="onScriptChange"/>
        <span class="h-input-addon">
          <span class="link" style="user-select: none" @click="openEditor">{{data.script?'去编辑':'去创建'}}</span>
        </span>
      </div>
    </FormItem>
    <FormItem label="前置函数" prop="perScript" single>
      <Select :datas="perMethods" keyName="id" titleName="title" v-model="data.perScript" :filterable="true"/>
    </FormItem>
    <FormItem label="功能描述" prop="description" required single>
      <Textarea type="text" v-model="data.description" placeholder="向AI描述函数的功能"/>
    </FormItem>
    <FormItem label="参数" prop="parameters" single>
      <div style="position: relative">
        <Table :datas="paramsTable">
          <TableItem title="参数名" :width="100">
            <template #default="{data}">
              <Input type="text" v-model="data.name"/>
            </template>
          </TableItem>
          <TableItem title="参数类型" :width="100">
            <template #default="{data}">
              <Select :datas="types" v-model="data.type"/>
            </template>
          </TableItem>
          <TableItem title="是否必填" :width="80">
            <template #default="{data}">
              <HSwitch v-model="data.required"/>
            </template>
          </TableItem>
          <TableItem title="参数描述" :width="200" >
            <template #default="{data}">
              <Input type="text" v-model="data.description"/>
            </template>
          </TableItem>
          <TableItem title="枚举" :width="200">
            <template #default="{data}">
              <TagInput v-model="data.enum"/>
            </template>
          </TableItem>
          <TableItem :width="80" align="center" fixed="right">
            <template #default="{data}">
              <LinkButtons>
                <Button @click="delParam(data)">删除</Button>
              </LinkButtons>
            </template>
          </TableItem>
        </Table>
        <span class="link table-button jeicon-add" @click="addParam">添加</span>
      </div>
    </FormItem>
    <FormItem label="返回值" prop="parameters" single>
      <div style="position: relative">
        <Table :datas="responseTable">
          <TableItem title="属性名" :width="100">
            <template #default="{data}">
              <Input type="text" v-model="data.name"/>
            </template>
          </TableItem>
          <TableItem title="属性类型" :width="100">
            <template #default="{data}">
              <Select :datas="types" v-model="data.type"/>
            </template>
          </TableItem>
          <TableItem title="属性描述" :width="200" >
            <template #default="{data}">
              <Input type="text" v-model="data.description"/>
            </template>
          </TableItem>
          <TableItem title="枚举" :width="200">
            <template #default="{data}">
              <TagInput v-model="data.enum"/>
            </template>
          </TableItem>
          <TableItem :width="80" align="center" fixed="right">
            <template #default="{data}">
              <LinkButtons>
                <Button @click="delRespProp(data)">删除</Button>
              </LinkButtons>
            </template>
          </TableItem>
        </Table>
        <span class="link table-button jeicon-add" @click="addResp">添加</span>
      </div>
    </FormItem>
    <FormItem label="举例" prop="examples" single>
      <Textarea v-model="data.examples" rows="3" v-autosize v-wordcount="1000"></textarea>
    </FormItem>
    <FormItem label="直接返回" prop="direct">
      <Switch type="text" v-model="data.direct"/>
    </FormItem>

  </Form>
</template>
<style scoped>
.table-button{
  position: absolute;
  right: 20px;
  top:20px;
  z-index: 20;
  user-select: none;
  font-size: 14px;
}
</style>

